<template>
    <div style="margin-top: 60px;">
        <div class="chart" v-show="ishuaiyun" id="myChart" style="width: 90vw;height: 600px;"></div>
        <div class="chart2" v-show="isnothuaiyun" id="myChart2" style="width: 90vw;height: 800px;"></div>
    </div>
</template>

<script>
import echarts from 'echarts'

//乘法
let multi = function (arg1, arg2) {
    var r1 = arg1.toString(), 
        r2 = arg2.toString(), 
        m, 
        resultVal, 
        d = arguments[2];
        m = (r1.split(".")[1] ? r1.split(".")[1].length : 0) + (r2.split(".")[1] ? r2.split(".")[1].length : 0);
        resultVal = Number(r1.replace(".", "")) * Number(r2.replace(".", "")) / Math.pow(10, m);
        return typeof d !== "number" ? Number(resultVal) : Number(resultVal.toFixed(parseInt(d)));
}
//除法
let devide = function (arg1, arg2) {
    var r1 = arg1.toString(), 
        r2 = arg2.toString(), 
        m, 
        resultVal, 
        d = arguments[2];
        m = (r2.split(".")[1] ? r2.split(".")[1].length : 0) - (r1.split(".")[1] ? r1.split(".")[1].length : 0)
        resultVal = Number(r1.replace(".", "")) / Number(r2.replace(".", "")) * Math.pow(10, m)
        return typeof d !== "number" ? Number(resultVal) : Number(resultVal.toFixed(parseInt(d)))
}

export default {
	props: ["chartData"],
	data(){
		return {
			maxWeightChangesArr: '',//最大增重范围
			minWeightChangesArr: '',//最小增重范围

			newWeeksArr: [],//x轴 40周
			newSeriesArr: [],

			maxYaxis: null,
            ishuaiyun: false,
            isnothuaiyun: true,
            ConfirrmTime: '',
            userHeight: '',
			maxNweight:66,
			minNweight:51  //孕前
		}
	},
	watch:{
		'chartData':{
            handler:function(val,oldval){
                let msg = val;
                this.ConfirrmTime = msg.dtBasic[0].ConfirrmTime
                if(msg.dtHeightAndWeight[0] != undefined){
                    this.userHeight = msg.dtHeightAndWeight[0].Height
                } else{
                    this.userHeight = 160
                }
                //孕前期
                //画孕前期的图
                //如果在怀孕期
                //再画一张图
                /***************************孕前期图表***********************/
                if(msg.dtPreWeightMonitor.length != ''){ //孕前期体重存在
                    let msg1 = msg.dtPreWeightMonitor.filter(e => e.Recorder === "项目测量")
                    let msg2 = msg.dtPreWeightMonitor.filter(e => e.Recorder === "自己")
                    let msg3 = msg.dtPreWeightMonitor.filter(e => e.Recorder === "其他健康服务机构")
                    let buquan = weeksArr => {
                        var xx = new Date(weeksArr[0])
                        var base = +xx;
                        var xxx = new Date(weeksArr[weeksArr.length-1])
                        var oneDay = 24 * 3600 * 1000;
                        var days = (+new Date(xxx.getFullYear(), xxx.getMonth()+1) - base) / oneDay + 1
                        var date = [];

                        var data = [Math.random() * 300];

                        for (var i = 1; i <= days; i++) {
                            var now = new Date(base);
                            base += oneDay
                            date.push([now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/'));
                        }
                        return date
                    }

                    let xx = []
                    // let lastDay
                    let week

                    let startDay
                    msg.dtPreWeightMonitor.forEach(e => {
	                    if(e.WEIGHT>this.maxNweight){
		                    this.maxNweight=e.WEIGHT
	                    }
	                    if(e.WEIGHT<this.minNweight){
	                    	this.minNweight=e.WEIGHT
	                    }
                        // 开始时间为入组时间
                        if(startDay){
                            startDay = new Date(startDay) > new Date(this.ConfirrmTime) ? this.ConfirrmTime : startDay
                        } else {
                            startDay = this.ConfirrmTime
                        }
                    })
                    let lastDay = +new Date(startDay) + 52*7*24*3600*1000
                    week = buquan([startDay,lastDay])


                    //体重参考值 起始点
                    this.weightStart = msg.dtPreWeightMonitor[0].WEIGHT ? msg.dtPreWeightMonitor[0].WEIGHT : 50

                    let BMIMin = 18.5
                    let BMIMax = 24.0
                    let b = devide(this.userHeight,100)//身高(米)
                    let c = multi(b,b)//身高的平方
                    let averageWeightMax = multi(c,BMIMax).toFixed(2)
                    let averageWeightMin = multi(c,BMIMin).toFixed(2)
                    let weightsArrayMax = []
                    let weightsArrayMin = []

                    //BMI 最大范围，最小范围
                    for(let i = 0; i < 53; i++){
                        weightsArrayMax.push([i,averageWeightMax,24.0])
                        weightsArrayMin.push([i,averageWeightMin,18.5])
                    }

                    this.weightMaxValue = this.weightStart + 10
                    if(averageWeightMax > this.weightMaxValue){
                        this.newYValue = averageWeightMax
                    } else{
                        this.newYValue = this.weightMaxValue
                    }
                    this.userHeightM = devide(this.userHeight,100)//身高(m)
                    this.userHeightMs = multi(this.userHeightM, this.userHeightM)//身高平方

                    let qq = msg => {
                        xx = msg.map((e,i,q) => [e.RECORD_DATE, e.WEIGHT, devide(e.WEIGHT, this.userHeightMs).toFixed(1)])
                        xx.push([lastDay,undefined,undefined])
                        if(this.firstDay){
                            this.firstDay = new Date(this.firstDay) < new Date(week[0]) ? this.firstDay : week[0]
                        } else{
                            this.firstDay = week[0]
                        }
                        xx.pop()
                        xx.forEach(e => {
                            let index
                            let cc = week.find((el, i) => {index = i; return +new Date(el) == +new Date(e[0])})
                            if(cc){
                                e[0] = index/7 + 1
                            }
                        })
                        return {
                            xx: xx,
                            week: week
                        }
                    }
                    let aaa = []
                    let bbb = []
                    let ccc = []
                    //项目测量数据
                    if(msg1.length != ''){
                        qq(msg1)
                        aaa = qq(msg1).xx
                    }
                    //自己测量数据
                    if(msg2.length != ''){
                        qq(msg2)
                        bbb = qq(msg2).xx
                    }
                    //其他健康服务机构数据
                    if(msg3.length != ''){
                        qq(msg3)
                        ccc = qq(msg3).xx
                    }
                    let arr = []
                    // BMI最大值 < 24
                    arr.push({
                        name:'BMI范围',
                        type:'line',
                        data: weightsArrayMax,//BMI值
                        itemStyle: {
                            normal: {
                                color: '#92EAC0'
                            },
                        },
                        smooth:false,
                    })

                    // BMI最大值 >= 18.5
                    arr.push({
                        name:'BMI范围',
                        type:'line',
                        data: weightsArrayMin,//BMI值
                        itemStyle: {
                            normal: {
                                color: '#92EAC0'
                            },
                        }
                    })

                    arr.push({
                        name:'项目测量',
                        type:'scatter',
                        data: aaa,//体重
                        itemStyle: {
                            normal: {
                                // color: ['#EAA17F', '#8FBEF2', '#8FBEF2', '#8FBEF2'][iii]
                                borderColor: '#8FBEF2',
                                borderWidth: 1,
                                color: '#8FBEF2'
                            },
                        }
                    })

                    arr.push({
                        name:'对象自测',
                        type:'scatter',
                        data: bbb,//体重
                        itemStyle: {
                            normal: {
                                borderColor: '#EAA17F',
                                borderWidth: 1,
                                color: 'transparent'
                            },
                        }
                    })

                    arr.push({
                        name:'机构测量',
                        type:'scatter',
                        data: ccc,//体重
                        itemStyle: {
                            normal: {
                                borderColor: '#467CD4',
                                borderWidth: 1,
                                color: 'transparent'
                            },
                        }
                    })

                    this.WEIGHTchanges = arr
                } else if(msg.dtPreWeightMonitor.length == ''){
                    this.firstDay = this.ConfirrmTime
                    //体重参考值 起始点
                    this.weightStart = 50
                    let BMIMin = 18.5
                    let BMIMax = 24.0
                    let b = devide(this.userHeight,100)//身高(米)
                    let c = multi(b,b)//身高的平方
                    let averageWeightMax = multi(c,BMIMax).toFixed(2)
                    let averageWeightMin = multi(c,BMIMin).toFixed(2)
                    let weightsArrayMax = []
                    let weightsArrayMin = []

                    //BMI 最大范围，最小范围
                    for(let i = 0; i < 53; i++){
                        weightsArrayMax.push([i,averageWeightMax,24.0])
                        weightsArrayMin.push([i,averageWeightMin,18.5])
                    }

                    this.weightMaxValue = 60//50+10
                    if(averageWeightMax > this.weightMaxValue){
                        this.newYValue = averageWeightMax
                    } else{
                        this.newYValue = this.weightMaxValue
                    }
                    let arr = []

                    // BMI最大值 < 24
                    arr.push({
                        name:'BMI范围',
                        type:'line',
                        data: weightsArrayMax,//BMI值
                        itemStyle: {
                            normal: {
                                color: '#92EAC0'
                            },
                        },
                        smooth:false, 
                    })

                    // BMI最大值 >= 18.5
                    arr.push({
                        name:'BMI范围',
                        type:'line',
                        data: weightsArrayMin,//BMI值
                        itemStyle: {
                            normal: {
                                color: '#92EAC0'
                            },
                        }
                    })
                    arr.push({
                        name:'项目测量',
                        type:'line',
                        data: [0],
                        itemStyle: {
                            normal: {
                                color: 'transparent'
                            },
                        },
                        tooltip: {
                            backgroundColor: '#fff'
                        }
                    })
                    arr.push({
                        name:'对象自测',
                        type:'line',
                        data: [0],
                        itemStyle: {
                            normal: {
                                color: 'transparent'
                            },
                        },
                        tooltip: {
                            backgroundColor: '#fff'
                        }
                    })
                    arr.push({
                        name:'机构测量',
                        type:'line',
                        data: [0],
                        itemStyle: {
                            normal: {
                                color: 'transparent'
                            },
                        },
                        tooltip: {
                            backgroundColor: '#fff'
                        }
                    })

                    this.WEIGHTchanges = arr
                }

                /***************************怀孕期图表***********************/
                let maxWeightChanges = msg.dtMaxWeightChanges
                let minWeightChanges = msg.dtMinWeightChanges

                let newMaxChanges = []
                let newMinChanges = []
                console.log(0)
                for (var i = 0; i < maxWeightChanges.length; i++) {
                    newMaxChanges.push(maxWeightChanges[i].WeightChange.toFixed(2))
                    newMaxChanges.concat(maxWeightChanges[i].WeightChange.toFixed(2))
                }

                for (var i = 0; i < minWeightChanges.length; i++) {
                    newMinChanges.push(minWeightChanges[i].WeightChange.toFixed(2))
                    newMinChanges.concat(minWeightChanges[i].WeightChange.toFixed(2))
                }
                
                this.maxWeightChangesArr = newMaxChanges;//最大增重范围
                this.minWeightChangesArr = newMinChanges;//最小增重范围

                let weeksArr = msg.dtMaxWeightChanges.reduce((a, e) => {
                    a.indexOf(e.PregnancyWeek) < 0 && a.push(e.PregnancyWeek)
                    return a
                }, [])

                weeksArr = weeksArr.sort((a, b) => a - b)
                this.newWeeksArr = weeksArr //x轴 40周

                let weekObj = {}

                weeksArr.forEach(e => weekObj[e] = 'null')


                let weeksArr2 = msg.dtWeightMonitor.reduce((a, e) => { //体重记录 详情
                    a.indexOf(e.PregnancyWeeks) < 0 && a.push(e.PregnancyWeeks)
                    return a
                }, [])


                weeksArr2 = weeksArr2.sort((a, b) => a - b)
                let obj = {
                    '项目测量': [],
                    '自己': [],
                    '其他健康服务机构': []
                }

                msg.dtWeightMonitor.forEach(e => {
                    try{
                        obj[e.Recorder||'项目测量'].push([e.PregnancyWeeks,e.WeightChange,e.RECORD_DATE.substring(0,10),e.WEIGHT,recorderNameFilter(e.Recorder)])  //添加点
                    }
                	catch(s){
                        console.log([e.PregnancyWeeks,e.WeightChange,e.RECORD_DATE.substring(0,10),e.WEIGHT,recorderNameFilter(e.Recorder)])
                        console.log(s)
                    }
                })
                console.log(9988)
                let arr = []
                let iii = 0
                let legend = []
                function recorderNameFilter(value){
                    switch (value){
                        case '自己':
                            return '对象自测'
                            break;
                        case '其他健康服务机构':
                            return '机构测量'
                            break;
                        default:
                            return '项目测量'
                            break;
                    }
                }

                function colorFilter(value){
                    switch (value){
                        case '对象自测':
                            return '#EAA17F'
                            break;
                        case '机构测量':
                            return '#467CD4'
                            break;
                        default:
                            return '#8FBEF2'
                            break;
                    }
                }
                for (let n in obj) {
                    let recordNames = recorderNameFilter(n)
                    let color = colorFilter(recordNames)
                    let recorderObj = {
                        name:recordNames,
                        type:'scatter',
                        data:[],
                        itemStyle: {
                            normal: {
                                // color: ['#EAA17F', '#8FBEF2', '#8FBEF2', '#8FBEF2'][iii]
                                borderColor: color,
                                borderWidth: 1,
                                color: recordNames == '项目测量' ? color : 'transparent'
                                // color: color
                            },
                        }
                    }
                    // iii++
                    legend.push(recordNames)
                    for (let n2 in obj[n]) {
                        if (obj[n][n2] != 'null') {
                            recorderObj.data.push(obj[n][n2])
                        } else {
                            recorderObj.data.push(undefined)
                        }
                    }
	                arr.push(recorderObj)
                    arr.push({
                        name:'增重范围',
                        type:'line',
                        data: this.maxWeightChangesArr,//最大增重范围
                        itemStyle: {
                            normal: {
                                color: '#92EAC0'
                            },
                        }
                    })
                    arr.push({
                        name:'增重范围',
                        type:'line',
                        data:this.minWeightChangesArr,//最小增重范围
                        itemStyle: {
                            normal: {
                                color: '#92EAC0'
                            },
                        }
                    })
                }
                if(msg.dtWeightMonitor.length <= 1){//体重测量变化值不存在时
                    if(msg.dtMaxWeightChanges.length == 0 || msg.dtMinWeightChanges.length == 0) {//增重范围变化为空
                        let arr2 = []
                        for(let i = 0; i< 41; i++){
                            arr2.push(i)
                        }
                        this.newWeeksArr = arr2
                        arr.push({
                            name:'增重范围',
                            type:'line',
                            data: [20],//最大增重范围
                            itemStyle: {
                                normal: {
                                    color: 'transparent'
                                },
                            },
                            tooltip: {
                                backgroundColor: '#fff'
                            }
                        })
                    }
                    //增重范围变化存在
                    arr.push({
                        name:'增重范围',
                        type:'line',
                        data: this.maxWeightChangesArr,//最大增重范围
                        itemStyle: {
                            normal: {
                                color: '#92EAC0'
                            },
                        }
                    })
                    arr.push({
                        name:'增重范围',
                        type:'line',
                        data: this.minWeightChangesArr,//最小增重范围
                        itemStyle: {
                            normal: {
                                color: '#92EAC0'
                            },
                        }
                    })

                    legend.push('项目测量', '对象自测', '机构测量')
                }
                this.newSeriesArr = arr
                this.legend = legend
                // }
                this.ishuaiyun = msg.dtBasic[0].Period != '1'

                //孕前转怀孕的时间为空，就是孕期入组的,孕期入组的，需要隐藏孕前的曲线
                if(this.ishuaiyun){
                    if(msg.dtBasic[0].TransforPeriodTime == undefined){
                        this.isnothuaiyun = false
                    }
                }

    			this.drawLine()
            },
            deep:true
		}
	},
	created(){

	},
	methods: {
	    drawLine(){
	       // 基于准备好的dom，初始化echarts实例
           let myChart = this.ishuaiyun ?echarts.init(document.getElementById('myChart')) : undefined;
	       let myChart2 =echarts.init(document.getElementById('myChart2'));

	       	let option = {
	           	title: {
	               	text: '怀孕期体重变化曲线',
	               	textStyle: {
	                   	fontSize: 16,
	                    color: '#333',
	                    fontWeight: 'normal'
	                },
                    x: 'center',
                    y: 0
	            },
	            legend: {
                    // data:['增重范围'].concat(this.legend),
	                data:[{
                        name: '增重范围',
                        icon: 'image://static/img/first_icon.png'
                    },{
                        name: '项目测量',
                        icon: 'image://static/img/second_icon.png'
                    },{
                        name: '对象自测',
                        icon: 'image://static/img/third_icon.png'
                    },{
                        name: '机构测量',
                        icon: 'image://static/img/forth_icon.png'
                    }],
	                y: '10%',
                    itemWidth: 15,
                    itemGap: 15,
                    selectedMode:false,
	            },
	            grid: {//网格位置,
	                left: '10%',
	                top: '20%',
	                right: '10%',
	                bottom: '15%',
	                width: '80%',
	                height: '60%'
	            },
	            toolbox: {
	                show: false,
	            },
	            xAxis: {
	                type: 'category',
	                name: '孕周',
	                nameLocation: 'start',
	                boundaryGap: true,
                    nameTextStyle:{
                        padding: [28,2,0,0]
                    },
	                data: this.newWeeksArr
	            },
	            yAxis: {
	                type: 'value',
	                name: '体重增长（kg）',
                    // min: 1,
                    axisLabel: {
                        // formatter: '{value}'
                        formatter: function (value, index) {
                            return value.toFixed(1)
                        }
                    },

	            },
                tooltip: {
                    formatter: params => {
                        if(Object.prototype.toString.call(params.data) == '[object Array]'){
                            return `
                                ${params.data[2]}<br />
                                孕${params.data[0]}周<br />
                                ${params.data[4]}<br />
                                体重${params.data[3]}kg<br>
                                增重${params.data[1]}kg<br>`
                        }
                        else{
                            return `增重范围<br />孕${params.dataIndex}周<br />增重${params.value}kg`
                        }
                                    
                    }
                },
	            series: this.newSeriesArr
	        };
            let _this = this;
            let option2 = {
                title: {
                    text: '孕前期体重变化曲线',
                    textStyle: {
                        fontSize: 16,
                        color: '#333',
                        fontWeight: 'normal'
                    },
                    x: 'center',
                    y: 0
                },
                legend: {
                    // data:['增重范围'].concat(this.legend),
                    data:[{
                        name: 'BMI范围',
                        icon: 'image://static/img/first_icon.png'
                    },{
                        name: '项目测量',
                        icon: 'image://static/img/second_icon.png'
                    },{
                        name: '对象自测',
                        icon: 'image://static/img/third_icon.png'
                    },{
                        name: '机构测量',
                        icon: 'image://static/img/forth_icon.png'
                    }],
                    y: '8%',
                    itemWidth: 15,
                    itemGap: 15,
                    selectedMode:false,
                },
                grid: {//网格位置,
                    left: '10%',
                    top: '16%',
                    right: '10%',
                    bottom: '5%',
                    width: '80%',
                    height: '60%'
                },
                toolbox: {
                    show: false,
                },
                xAxis: {
                    type: 'value',
                    name: '周',
                    interval: 1,
                    max: 52,
                    nameLocation: 'start',
                    boundaryGap: true,
                    nameTextStyle:{
                        padding: [28,2,0,0]
                    },
                },
                yAxis: {
                    type: 'value',
                    name: '体重(kg)',
                    max: this.maxNweight+10,
                    min: this.minNweight - 5,
                    // interval: 1,
                    axisLabel: {
                        formatter: function (value, index) {
                            return value.toFixed(1)
                        }
                    },
                },
                tooltip: {

                    trigger: 'item',
                    formatter: params => {
                            var day = Math.floor(params.data[0])
                            var dayDif = (params.data[0]*7 - 7) * 1000 * 60 * 60 * 24
                            var firstDay = _this.firstDay
                            var date = new Date(+new Date(firstDay) + dayDif)
                            var dateStr = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
                            //日期: ${dateStr}<br>
                            if(firstDay){
                                return `
                                    ${dateStr}<br>
                                    ${params.seriesName}<br>
                                    体重${params.data[1]}kg<br>
                                    BMI=${params.data[2]}<br>
                                    
                                `
                            } else {
                                return `
                                    ${dateStr}<br>
                                    ${params.seriesName}<br>
                                    体重${params.data[1]}kg<br>
                                    BMI=${params.data[2]}<br>
                                `
                            }
                    }
                },
                series: this.WEIGHTchanges
            };
	        // 绘制图表
	        if (option && typeof option === "object") {
                this.ishuaiyun && myChart.setOption(option, true); // 怀孕期
	            this.isnothuaiyun && myChart2.setOption(option2, true); // 孕前期
	        }
	        window.onresize = () => {
                this.ishuaiyun && myChart.resize();
	            this.isnothuaiyun && myChart2.resize();
	        };
	    }
	}
}
</script>
<style>
   
</style>
